# -*- coding: utf-8 -*-

# Copyright: (c) 2007, Jarek Zgoda <jzgoda@o2.pl>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.

"""
Last.FM Client Plugin for QuodLibet.
"""

__revision__ = '$Id: lastfmcli.py 41 2007-05-06 21:25:38Z jarek.zgoda $'

import os
import threading
from xml.sax import saxutils

import gobject
import gtk
from gtk import glade

import config
from plugins.songsmenu import SongsMenuPlugin
import lastfmsvc


class LastFMClientWindow(gtk.Window):

    def __init__(self, song):
        self.song = song
        # textual data of song, escaped
        self.song_data = {}
        for k, v in song.items():
            if not k.startswith('~'):
                self.song_data[k] = saxutils.escape(v)
        gtk.Window.__init__(self)
        self.set_border_width(2)
        self.set_title('LastFM client')
        self.set_default_size(420, 360)
        glade_file = os.path.join(os.path.dirname(__file__), 'lastfmcli.glade')
        self.w_tree = glade.XML(glade_file, 'box_main')
        self.w_tree.signal_autoconnect(self)
        box = self.w_tree.get_widget('box_main')
        box.unparent()
        self.add(box)
        self.w_tree.get_widget('combo_what_to_tag').set_active(0)
        self.w_tree.get_widget('combo_what_to_recommend').set_active(0)
        tag_list_model = gtk.ListStore(str)
        tag_list = self.w_tree.get_widget('list_tags')
        tag_list.set_model(tag_list_model)
        col = gtk.TreeViewColumn('Tag', gtk.CellRendererText(), text=0)
        tag_list.append_column(col)
        self.username = \
            config.get('plugins', 'scrobbler_username').decode('utf-8')
        self.password = \
            config.get('plugins', 'scrobbler_password').decode('utf-8')
        self.remote_service = \
            lastfmsvc.LastFMService(self.username, self.password)
        self.remote_data = lastfmsvc.AudioscrobblerData()
        self.show_all()

    def on_combo_what_changed(self, *args, **kw):
        combo = args[0]
        model = combo.get_model()
        item_name = model.get_value(combo.get_active_iter(), 0).lower()
        if item_name == 'artist':
            text = u'<b>%(artist)s</b>'
        elif item_name == 'album':
            text = u'<b>%(artist)s - %(album)s</b>'
        else:
            text = u'<b>%(artist)s - %(title)s</b>'
        if combo.get_name() == 'combo_what_to_tag':
            label = self.w_tree.get_widget('lbl_tag_item_name')
        elif combo.get_name() == 'combo_what_to_recommend':
            label = self.w_tree.get_widget('lbl_recommend_item_name')
        label.set_markup(text % self.song_data)
        entry = self.w_tree.get_widget('entry_tags')
        entry.set_text('')
        tree = self.w_tree.get_widget('list_tags')
        model = tree.get_model()
        if model:
            model.clear()
        user_thread = threading.Thread(target=self._get_tags,
            args=(self.song_data, item_name, True))
        user_thread.setDaemon(True)
        user_thread.start()
        global_thread = threading.Thread(target=self._get_tags,
            args=(self.song_data, item_name, False))
        global_thread.setDaemon(True)
        global_thread.start()

    def _get_tags(self, song_data, what, user_tags):
        artist = song_data['artist']
        album = song_data['album']
        track = song_data['title']
        if what == 'artist':
            if user_tags:
                tags = self.remote_data.get_user_artist_tags(self.username, artist)
            else:
                tags = self.remote_data.get_artist_tags(artist)
        elif what == 'album':
            if user_tags:
                tags = self.remote_data.get_user_album_tags(self.username, artist, album)
            else:
                tags = self.remote_data.get_album_tags(artist, album)
        else:
            if user_tags:
                tags = self.remote_data.get_user_track_tags(self.username, artist, track)
            else:
                tags = self.remote_data.get_track_tags(artist, track)
        if user_tags:
            gobject.idle_add(self._add_user_tags, tags)
        else:
            gobject.idle_add(self._add_global_tags, tags)

    def _add_user_tags(self, tags):
        entry = self.w_tree.get_widget('entry_tags')
        tag_names = [tag[0] for tag in tags]
        entry.set_text(u', '.join(tag_names))

    def _add_global_tags(self, tags):
        tree = self.w_tree.get_widget('list_tags')
        model = tree.get_model()
        for tag in tags:
            model.append((tag[0], ))

    # signal handlers
    def on_list_tags_button_press_event(self, *args, **kw):
        widget, event = args
        if event.button == 1 and event.type == gtk.gdk._2BUTTON_PRESS:
            store, iterator = widget.get_selection().get_selected()
            new_tag = store.get_value(iterator, 0)
            print new_tag
            entry = self.w_tree.get_widget('entry_tags')
            tags = []
            tags_text = entry.get_text().strip()
            if tags_text:
                tags = tags_text.split(',')
            tags = [tag.strip() for tag in tags]
            tags.append(new_tag)
            entry.set_text(', '.join(tags))


class LastFMClient(SongsMenuPlugin):
    PLUGIN_ID = "Last.fm client"
    PLUGIN_NAME = _("Last.fm webservice client")
    PLUGIN_DESC = _("Last.fm user services client")
    PLUGIN_ICON = gtk.STOCK_CONNECT
    PLUGIN_VERSION = "0.0.0"

    plugin_single_song = LastFMClientWindow
